package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.TownClassify;
import cn.stylefeng.guns.modular.business.enums.TownClassifyExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.TownClassifyMapper;
import cn.stylefeng.guns.modular.business.pojo.TownClassifyRequest;
import cn.stylefeng.guns.modular.business.service.TownClassifyService;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 城镇分类表业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/25 16:46
 */
@Service
public class TownClassifyServiceImpl extends ServiceImpl<TownClassifyMapper, TownClassify> implements TownClassifyService {

	@Override
    public void add(TownClassifyRequest townClassifyRequest) {
        TownClassify townClassify = new TownClassify();
        BeanUtil.copyProperties(townClassifyRequest, townClassify);
        this.save(townClassify);
    }

    @Override
    public void del(TownClassifyRequest townClassifyRequest) {
        TownClassify townClassify = this.queryTownClassify(townClassifyRequest);
        this.removeById(townClassify.getId());
    }

    @Override
    public void edit(TownClassifyRequest townClassifyRequest) {
        TownClassify townClassify = this.queryTownClassify(townClassifyRequest);
        BeanUtil.copyProperties(townClassifyRequest, townClassify);
        this.updateById(townClassify);
    }

    @Override
    public TownClassify detail(TownClassifyRequest townClassifyRequest) {
        return this.queryTownClassify(townClassifyRequest);
    }

    @Override
    public PageResult<TownClassify> findPage(TownClassifyRequest townClassifyRequest) {
        LambdaQueryWrapper<TownClassify> wrapper = createWrapper(townClassifyRequest);
        Page<TownClassify> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }

    @Override
    public List<TownClassify> findList(TownClassifyRequest townClassifyRequest) {
        LambdaQueryWrapper<TownClassify> wrapper = this.createWrapper(townClassifyRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/25 16:46
     */
    private TownClassify queryTownClassify(TownClassifyRequest townClassifyRequest) {
        TownClassify townClassify = this.getById(townClassifyRequest.getId());
        if (ObjectUtil.isEmpty(townClassify)) {
            throw new ServiceException(TownClassifyExceptionEnum.TOWNCLASSIFY_NOT_EXISTED);
        }
        return townClassify;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/25 16:46
     */
    private LambdaQueryWrapper<TownClassify> createWrapper(TownClassifyRequest townClassifyRequest) {
        LambdaQueryWrapper<TownClassify> queryWrapper = new LambdaQueryWrapper<>();

        Long id = townClassifyRequest.getId();
        String townSecond = townClassifyRequest.getTownSecond();
        String secondCode = townClassifyRequest.getSecondCode();
        String townThird = townClassifyRequest.getTownThird();
        String thirdCode = townClassifyRequest.getThirdCode();
        String belongProvince = townClassifyRequest.getBelongProvince();
        String detailedInformation = townClassifyRequest.getDetailedInformation();
        String townCoord = townClassifyRequest.getTownCoord();

        queryWrapper.eq(ObjectUtil.isNotNull(id), TownClassify::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(townSecond), TownClassify::getTownSecond, townSecond);
        queryWrapper.like(ObjectUtil.isNotEmpty(secondCode), TownClassify::getSecondCode, secondCode);
        queryWrapper.like(ObjectUtil.isNotEmpty(townThird), TownClassify::getTownThird, townThird);
        queryWrapper.like(ObjectUtil.isNotEmpty(thirdCode), TownClassify::getThirdCode, thirdCode);
        queryWrapper.like(ObjectUtil.isNotEmpty(belongProvince), TownClassify::getBelongProvince, belongProvince);
        queryWrapper.like(ObjectUtil.isNotEmpty(detailedInformation), TownClassify::getDetailedInformation, detailedInformation);
        queryWrapper.like(ObjectUtil.isNotEmpty(townCoord), TownClassify::getTownCoord, townCoord);

        return queryWrapper;
    }

    /**
     * 获取城镇分类
     *
     * @author zhangyaowen
     * @date 2021/10/25 16:46
     */
    @Override
    public List<Map<String,Object>> findChoose() {
        LambdaQueryWrapper<TownClassify> queryWrapper = new LambdaQueryWrapper<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<TownClassify> list= this.list(queryWrapper);
        for(TownClassify townClassify : list){

            Map<String, Object> map = new HashMap<String, Object>();
//            if(! "null".equals(townClassify.getTownSecond())  || !"".equals(townClassify.getTownSecond()) ){
            if(townClassify != null) {
                if (townClassify.getTownSecond() != null) {
                    map.put("label", townClassify.getTownSecond());
                    map.put("value", townClassify.getSecondCode());
                    mapList.add(map);
                }
            }
        }
        //List<map>去重 生成新的list
        ArrayList<Map<String, Object>> town = mapList.stream()
                .collect(Collectors
                        .collectingAndThen(Collectors
                                .toCollection(() -> new TreeSet<>(new Comparator<Map<String, Object>>() {
                                    @Override    //重写比较器
                                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                                        if (o1.get("label").equals(o2.get("label"))) {
                                            return 0;
                                        }
                                        return 1;
                                    }

                                })), ArrayList::new));

        return town;
    }
    @Override
    public List<Map<String,Object>> findTown(String secondCode) {
        String[] secondCodes = {};
        if(!secondCode.equals("") ) {
            secondCodes = StrUtil.splitToArray(secondCode, ";");
        }
        LambdaQueryWrapper<TownClassify> queryWrapper = createTownWrapper(secondCodes);
        List<TownClassify> list= this.list(queryWrapper);

        List<Map<String,Object>> mapList = new ArrayList<>();

        for(TownClassify townClassify : list){

            Map<String, Object> map = new HashMap<String, Object>();
            if(!townClassify.getTownSecond().equals("")){
                map.put("town",townClassify.getTownThird());
                map.put("coord",townClassify.getTownCoord());
                byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
                SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
                String jmid = YunHeKey.YHCZ+townClassify.getTownThird();
                String encryptHex = aes.encryptHex(jmid);
                map.put("id",encryptHex);
                mapList.add(map);
            }
        }


        return mapList;
    }


    /**
     * 创建城镇分类查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<TownClassify> createTownWrapper(String[] towns) {
        LambdaQueryWrapper<TownClassify> queryWrapper = new LambdaQueryWrapper<TownClassify>();
        if( towns.length !=0) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < towns.length; i++) {
                    String town = towns[i];
                    wrapper.eq(ObjectUtil.isNotEmpty(town), TownClassify::getSecondCode, town);
                    if (i != towns.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        return queryWrapper;//.orderByDesc(FigureInfo::getHistoryDating);
    }

    @Override
    public String findCode(String name) {
        LambdaQueryWrapper<TownClassify> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ObjectUtil.isNotEmpty(name), TownClassify::getTownThird, name).select(TownClassify::getThirdCode);
        List<TownClassify>  list = this.list(queryWrapper);

        return list.get(0).getThirdCode();
    }

}